﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using FCISPlus.Client.Communicator;

namespace FCISPlus.Client.UI
{
    public partial class SendMessage : Form
    {
        int? friendID;
        IFCISPlusClientCommunicator communicator;
        public SendMessage(IFCISPlusClientCommunicator communicator, int? friendID)
        {
            InitializeComponent();
            this.communicator = communicator;
            this.friendID = friendID;
        }

        private void SendMessage_Load(object sender, EventArgs e)
        {
            FCISPlus.Server.Database.User[] users = this.communicator.GetFriends();
            this.cmbFriends.DataSource = users;
            this.cmbFriends.DisplayMember = "Username";
            this.cmbFriends.ValueMember = "UserID";
            if (this.friendID.HasValue)
            {
                this.cmbFriends.Enabled = false;
                this.cmbFriends.SelectedValue = this.friendID;
                if (cmbFriends.Items.Count == 0)
                {
                    this.btnSendMessage.Enabled = false;
                }
            }
        }

        private void btnSendMessage_Click(object sender, EventArgs e)
        {
            if (this.cmbFriends.SelectedItem != null && !string.IsNullOrEmpty(this.txtMessage.Text))
            {
                int friendID = (int)this.cmbFriends.SelectedValue;
                FCISPlus.Server.Database.User friend =
                    this.communicator.GetFriends().Where(x => x.UserID == friendID).ToArray<FCISPlus.Server.Database.User>()[0];
                this.communicator.SendMessage(friend, this.txtMessage.Text);
                this.Close();
            }
            else
            {
                string errorMsg = "";
                if (this.cmbFriends.SelectedItem == null)
                {
                    errorMsg += "Select a friend to send the message to.";
                    errorMsg += Environment.NewLine;
                }
                if (string.IsNullOrEmpty(this.txtMessage.Text))
                {
                    errorMsg += "Type the message";
                }
                MessageBox.Show(errorMsg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
    }
}
